
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import PageNumberPagination
from .serializers import GatheringModelSerializer
from .models import Gathering
from rest_framework.views import APIView
from rest_framework.response import Response


# Create your views here.
class GatheringPage(PageNumberPagination):
    max_page_size = 20
    page_size = 10
    page_size_query_param = 'page'
    page_query_param = 'pagesize'


class GatheringJoinView(APIView):
    def post(self, request, pk):
        gather = Gathering.objects.get(pk=pk)
        users = gather.users.all()
        user = request.user
        if user in users:
            gather.users.remove(user)
            gather.save()
            message = "取消成功"
            success = True
        else:
            gather.users.add(user)
            gather.save()
            message = "参加成功"
            success = True

        data = {
            "message": message,
            "success": success
        }
        return Response(data=data)


class GatheringModelViewSet(ModelViewSet):
    queryset = Gathering.objects.all()
    serializer_class = GatheringModelSerializer
    pagination_class = GatheringPage
